package com.zwj.interview.BFS;

import java.util.*;

/**
 * @Author: Zwj
 * @Date: 2022/9/19 16:29
 * 这是典型的BFS遍历
 */
public class 之字形层序遍历二叉树 {

    public List<List<Integer>> zigzagLevelorder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        //记录遍历到的层数，偶数层不变，奇数层就要翻转一下list
        int level = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            //奇数层翻转list
            if (level % 2 == 1) {
                Collections.reverse(list);
            }
            //一层遍历完了，加入结果集
            result.add(list);
            //一层结束，层数加一
            level++;
        }
        return result;
    }


}